package com.haighcom.service.impl;

import com.haighcom.mapper.OrderSettingDao;
import com.haighcom.model.OrderSetting;
import com.haighcom.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> data) {
        if (data != null && data.size() >0){
            for (OrderSetting orderSetting : data) {
                long countByOrderDate = orderSettingDao.findCOuantByOrderDate(orderSetting.getOrderDate());
                if (countByOrderDate>0){
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else{
                    orderSettingDao.add(orderSetting);
                }

            }
        }


    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) { //yyyy-MM
        String begin = date+"-1";//2024-6-1
        String[] split = date.split("-");
        String year = split[0];
        String month = split[1];
        int days = getMonthDays(Integer.parseInt(year), Integer.parseInt(month));
        String end = date + "-"+days;
        HashMap<String, String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        ArrayList<Map> result = new ArrayList<>();
        if (list != null && list.size() >0){
            for (OrderSetting orderSetting : list) {
                HashMap<String, Object> m = new HashMap<>();
                m.put("date",orderSetting.getOrderDate().getDate());
                m.put("number",orderSetting.getNumber());
                m.put("reservations",orderSetting.getReservations());
                result.add(m);
            }

        }
        return result;
    }


    public static int getMonthDays(int year, int month) {
        if (month == 2) {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                return 29;
            } else {
                return 28;
            }
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        } else {
            return 31;
        }
    }
}
